<?php

namespace App\Services;

use common\utils\RedisKeys;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Order;

//帮助公告service
class OrderService
{
    /**
     * 线下代理转账出款
     *
     * @var int
     */
    const TYPE_PAYOUT_TRANSFER = 402;

    /**
     * 当月用户各个游戏的有效投注总金额
     * @param int $id
     * @param array $partners
     * @return array
     */
    public static function getBettingMoneyByPartner($id, $partners)
    {
        $params['status'] = OrderEnum::STATUS_RECKONED;
        $params['time_begin'] = date('Y-m-01 00:00:00', time());
        $params['time_end'] = date('Y-m-d H:i:s', time());
        $params['user_id'] = $id;
        list($where, $between) = self::parseParams($id, $params);
        $orders = Order::select([
            'partner_id',
            DB::raw('sum(bet_amount) as bet_amount')
        ])
            ->where($where)
            ->whereBetween('bet_time', $between)
            ->groupBy("partner_id")
            ->get()
            ->toArray();
        foreach ($partners as $partnerId => $partner) {
            $re[$partnerId] = [
              'partner_id' => $partnerId,
              'partner_name' => $partner,
              'bet_amount' => 0
            ];
            foreach ($orders as $order) {
                if($partnerId == $order['partner_id']){
                    $re[$partnerId]['bet_amount'] = $order['bet_amount'];
                }
            }
        }
        return array_values($re);
    }

    public static function getOrderMenu()
    {
        //游戏注单类型, 1:电子，2:视讯，3:体育 4:电竞 5:彩票 6:棋牌
        $arr = [
            [
                'game_type' => '1',
                'name' => __('message.cgame'),
                'id_name' => 'egame'
            ],
            [
                'game_type' => '2',
                'name' => __('message.live_video'),
                'id_name' => 'live'
            ],
            [
                'game_type' => '3',
                'name' => __('message.sport'),
                'id_name' => 'sports'
            ],
            [
                'game_type' => '4',
                'name' => __('message.bi_game'),
                'id_name' => 'esport'
            ],
            [
                'game_type' => '5',
                'name' => __('message.fast_standard'),
                'id_name' => 'lottery'
            ],
            [
                'game_type' => '6',
                'name' => __('message.chess'),
                'id_name' => 'chess'
            ],
        ];
        //根据厅后台设置，隐藏和显示菜单
        $navigation = Redis::get(RedisKeys::SET_GLOBAL);
        $navigation = json_decode($navigation, true);
        if (!$navigation || !isset($navigation['menu'])) {
            return "false";
        }
        foreach ($arr as $kr => $vr) {
            foreach ($navigation['menu'] as $kd => $vd) {
                if (strcasecmp($vd['id'], $vr['id_name']) == 0 && $vd['val'] == false) {
                    unset($arr[$kr]);
                }
            }
        }
        /*        foreach($arr as $ke =>$val){
                    //兼容日博电竞数据
                    if(isset($tingInfo['hall_name']) && $tingInfo['hall_name'] == 'rb' && $val['id_name'] =='lottery'){
                        unset($arr[$ke]);
                    }
                }*/
        array_unshift($arr, ['name' => '全部']);
        $arr = array_values($arr);
        return $arr;
    }

    public static function parseParams($userId, $params)
    {
        $where[] = ['user_id', '=', $userId];
        $between = [];
        // 参数校验
        if (isset($params['time_begin'])) {
            $between['time_begin'] = date('Y-m-d H:i:s', strtotime($params['time_begin']));
        }
        if (isset($params['time_end'])) {
            $between['time_end'] = date('Y-m-d H:i:s', strtotime($params['time_end']));
        }
        //中奖状态
        if (isset($params['win_status'])) {
            if ($params['win_status'] == 2) $where[] = ['prize', '<=', 0];
            if ($params['win_status'] == 1) $where[] = ['prize', '>', 0];
        }
        foreach ([
                     'game_type',//游戏注单类型, 1:电子，2:真人，3:体育 4:电竞 5:彩票 6:棋牌
                     'partner_id',//游戏类型 partner表的id关联
                     'order_number',//注单号
                     'status'
                 ] as $field) {
            if (!isset($params[$field])) continue;
            $where[] = [$field, '=', $params[$field]];
        }
        return [$where, $between];
    }

    public static function getResult($userId, $params)
    {
        $page = isset($attrs['page']) ? $params['page'] : 1;
        $pageSize = isset($attrs['page_size']) ? $params['page_size'] : 20;

        // 参数格式化
        list($where, $between) = self::parseParams($userId, $params);
        $select = [
            'id',
            'username',
            'partner_account',
            'game_name',
            'created_at',
            'order_number',
            'bet_amount',
            'partner_name',
            'validbet',
            'prize',
            'profit',
            'bet_time',
            'status as state',
            'bet_content',//投注内容与结果等内容拼接
            'source'
        ];
        $sqlObj = Order::select($select)->where($where);
        if (!empty($between)) {
            $sqlObj->whereBetween('bet_time', $between);
        }
        return get_page_data($sqlObj, $page, $pageSize);
    }

    public static function getTotalMoney($userId, $params)
    {
        // 参数格式化
        list($where, $between) = self::parseParams($userId, $params);
        $select = [
            DB::raw('sum(bet_amount) as bet_amount'),
            DB::raw('sum(validbet) as validbet'),
            DB::raw('sum(prize) as send_prize'),
            DB::raw('sum(profit) as lose_earn')
        ];
        $sqlObj = Order::select($select)->where($where);
        if (!empty($between)) {
            $sqlObj->whereBetween('bet_time', $between);
        }
        return $sqlObj->first()->toArray();
    }

    /**
     * 获取有效投注(注：between区间不包括右边界)
     * @param $userId
     * @param $params
     * @return array
     */
    public static function getEffectiveBetting($userId, $params)
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 20;
        $reckonTime = [
            date('Y-m-d 00:00:00', strtotime($params['startTime'])),
            date('Y-m-d 00:00:00', strtotime('+1 days', strtotime($params['endTime'])))
        ];

        $where = ['user_id' => $userId];
        if (!empty($params['gameType'])) {
            $where['game_type'] = $params['gameType'];
        }

        $select = [
            DB::raw('DATE_FORMAT(`reckon_time`, "%Y-%m-%d") as reckonTime'),
            DB::raw('SUM(`bet_amount`) AS betAmount'),
            DB::raw('SUM(`validbet`) AS validBet'),
            DB::raw('SUM(`prize`) AS prize'),
            DB::raw('SUM(`profit`) AS profit')
        ];

        $query = Order::select($select)->where($where)->whereBetween('reckon_time', $reckonTime)->groupBy('reckonTime')->orderBy('reckonTime', 'DESC');
        $ret = get_page_data($query, $page, $pageSize);
        $ret['subTotalMoney'] = [
            'betAmount' => array_sum(array_column($ret['list'], 'betAmount')),
            'validBet' => array_sum(array_column($ret['list'], 'validBet')),
            'prize' => array_sum(array_column($ret['list'], 'prize')),
            'profit' => array_sum(array_column($ret['list'], 'profit')),
        ];

        $summary = Order::select($select)->where($where)->whereBetween('reckon_time', $reckonTime)->first()->toArray();
        $ret['totalMoney'] = [
            'betAmount' => $summary['betAmount'] ?? 0,
            'validBet' => $summary['validBet'] ?? 0,
            'prize' => $summary['prize'] ?? 0,
            'profit' => $summary['profit'] ?? 0,
        ];

        return $ret;
    }
}
